<?php
// This mail.php (Version 1.5d) code is a substantial modification of code originally released by cscartman (Cody Selzer) at www.codewalkers.com
// as freeware. The code has been considerably modified and extended for use in wikka wiki by GmBowen for a SSHRC research project.
// Modifications & additions by GmBowen released under GPL.
// Use: {{mail}} (no parameters). Needs: MySQL database tables (2) & class for pagination ("page.inc.php") placed in
// directory "scripts" in wikka root.
// The line below can be placed in php tags & added to the header after <h2> to provide an indication in the header of when there's mail.
// if (mysql_num_rows(mysql_query("SELECT status FROM ".$this->config["table_prefix"]."mail where UserTo='".$this->GetUserName()."' and folder='inbox' and status='unread' and viewrecipient='Y' LIMIT 1"))!=0) {echo "<a title='You have mail.'><font color=Red><strong>*</strong></font></a>";}

// includes functions for doing pagination of "sent" & "inbox" messages
include_once("scripts/page.inc.php");

$pagename = $this->MiniHref($method, $tag);
$link = $this->config["base_url"].$this->MiniHref($method, $tag);
$userfrom = $this->GetUserName();
$pagenum=$_GET['page'];
$username = $userfrom;
$folder=$_GET['folder'];
$which=$_REQUEST['whichfolder'];
if (!$folder) {$folder=$which;}
$fltrset=$_GET['fltrset'];
$msg_id=$_GET['mail_id'];
$filter=$_GET['fltr'];
$move2folder = $_REQUEST[move2folder];
$action=$_GET['action'];
$subject=$_GET[subject];
$mail_id=$msg_id;
$id=$_GET['id'];
$to=$_GET['to'];
?>

<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
countfield.value = maxlimit - field.value.length;
}
// End -->
</script>

<table><tr><td>|</td><td> <a href="<?php echo $link; ?>?action=inbox">Inbox</a> </td><td>|</td><td> <a href="<?php echo $link; ?>?action=compose">Compose</a> </td><td>|</td><td>

<?php
$str = "SELECT DISTINCT info FROM ".$this->config["table_prefix"]."mailinfo WHERE type='folder' and owner='$username' ORDER BY info ASC";
$resultdrop = mysql_query($str);
echo "<form method='post' action=\"$link\"><select name=\"whichfolder\">";
       while ($row = mysql_fetch_array($resultdrop)) {
        extract ($row);

            if($_REQUEST[whichfolder] == $info) {
               echo "<option selected value=\"$info\">$info</option>";
            }else {
               echo "<option value=\"$info\">$info</option>";
            }
       }
   echo "</select><input type='submit' value='View'></form>";
?>
</td><td>|</td><td> <a href="<?php echo $link; ?>?action=sent">Sent</a> </td><td>|</td><td> Manage <a href="<?php echo $link; ?>?action=folders">Folders</a> / <a href="<?php echo $link; ?>?action=contacts">Contacts</a> </td><td>| </td><td><a href="<?php echo $link; ?>?action=users">Users</a> <td>| <a href="<?php echo $link; ?>?action=help">Help</a></td> <td>|</td></td></tr></table>

<?php
if ($action=="compose" || $action=="forward" || $action=="contacts" || $action=="folders" || $action=="users" || $action=="help" || $action=="reply" || $action=="delete" || $action=="compose2"){echo "";
    } else {
    if ($action=="inbox" || (($action=="" || $action=="view") && $_REQUEST['whichfolder']=="" && $folder=="")) {$which2="<a href=".$link."&amp;page=".$pagenum.">In-box</a>";}
    elseif ($action=="sent" || $action=="view2") {$which2="<a href=".$link."?action=sent&amp;page=".$pagenum.">Sent Mail</a>";} elseif (folder!="") {$which=$folder; $which2="<a href=".$link."&folder=".$folder.">".$which."</a>";}
    echo "<strong>Folder:</strong>&nbsp;&nbsp;".$which2;
}


// code for moving messages to folders
if ($move2folder) {
 $query="UPDATE ".$this->config["table_prefix"]."mail SET folder='$move2folder' WHERE UserTo='$username' AND mail_id='$mail_id'";
 $query or die("An error occurred resulting that this message has not been marked read.");
 $rs = mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET folder='$move2folder' WHERE mail_id='$mail_id' AND UserTo='$username'");
 if($query) {
   echo "<br /><strong>Message moved to ".$move2folder." folder.</strong>";
   } else {
   echo "The message wasn't moved.";
   }
}

// shows inbox
elseif(($action=='' || $action=='inbox') && $_REQUEST['whichfolder']=='' && (!$folder)) {
 if ($filter==1) {$search="and fltr1='1' ";} elseif ($filter==2) {$search="and fltr2='1' ";} elseif ($filter==3) {$search="and fltr3='1' ";} elseif ($filter==N) {$search="and fltr1='0' and fltr2='0' and fltr3='0' ";} else {$search="";}
 // setting the filter conditions into the database
 $queryfil="SELECT fltr1,fltr2,fltr3,mail_id FROM ".$this->config["table_prefix"]."mail where UserTo='$username' and folder='inbox' and viewrecipient='Y' ORDER BY DateSent DESC";
 $resultfil=mysql_query($queryfil) or die ("cant do it");
 while ($row=mysql_fetch_array($resultfil)) {
   // code to set filters in database
    if (($fltrset) && ($row[mail_id]==$msg_id)) {
       // code to determine setting of filters on server
       if ($row[fltr1]!=1) {$fltrvar1=1;} else {$fltrvar1=0;}
       if ($row[fltr2]!=1) {$fltrvar2=1;} else {$fltrvar2=0;}
       if ($row[fltr3]!=1) {$fltrvar3=1;} else {$fltrvar3=0;}
       // code to set which filter is being set
       if ($fltrset==1) {$fltr="fltr1"; $set=$fltrvar1;} elseif ($fltrset==2) {$fltr="fltr2"; $set=$fltrvar2;} elseif ($fltrset==3) {$fltr="fltr3"; $set=$fltrvar3;}
       mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET ".$fltr."=".$set." WHERE mail_id='$msg_id' AND UserTo='$username'");
    }
 }
  $query="SELECT * FROM ".$this->config["table_prefix"]."mail where UserTo='$username' ".$search."and folder='inbox' and viewrecipient='Y' ORDER BY DateSent DESC";
  $result=mysql_query($query) or die ("cant do it");
 echo "<table cellpadding='2' cellspacing='3' width='850' valign='top'>";
       //needed for pagination of sent box
       $record_per_page=10;
       $scroll=3;
    $total_records=mysql_num_rows($result);
    $page=new Page(); //creating new instance of Class Page
    $link2=$link."?action=inbox";

    // to paginate the "inbox" page messages
    echo "<tr><td colspan='4' align='center'>";   
     if ($total_records>$record_per_page) {
         $page->set_page_data($link2,$total_records,$record_per_page,$scroll,true,true,true);
      $result=mysql_query($page->get_limit_query($query));
      echo $page->get_page_nav();
      }
    echo "</td></tr>";
  echo  "<tr bgcolor=#dddddd>\n";
  echo  "<td width='420'><table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td>&nbsp;Message Topic:</td><td align='right'>";
   // sets underline on filter if chosen
   if ($filter==1) {$red="<u>*</u>";} else {$red="*";}
   if ($filter==2) {$blue="<u>*</u>";} else {$blue="*";}
   if ($filter==3) {$green="<u>*</u>";} else {$green="*";}
   if ($filter=="N") {$none="<u>N</u>";} else {$none="N";}
  echo  "<a href=".$link." title='Shows ALL of the messages.'><strong>A</strong></a>&nbsp;<a href=".$link."?fltr=N title='Shows messages with NO star markers.'><strong>".$none."</strong></a>&nbsp;<a href=".$link."?fltr=1 title='Shows messages with a RED star marker.'><font color='red'><strong>".$red."</strong></font></a>&nbsp;<a href=".$link."?fltr=2 title='Shows messages with a BLUE star marker.'>";
  echo  "<font color='blue'><strong>".$blue."</strong></font></a>&nbsp;<a href=".$link."?fltr=3 title='Shows messages with a GREEN star marker.'><font color='green'><strong>".$green."</strong></font></a></td></tr></table></td>\n";
  echo  "<td width='85'>&nbsp;Sender:</td>\n";
  echo  "<td width='155'>&nbsp;Move to Folder:</td>\n";
  echo  "<td>&nbsp;Delete:</td>\n";
  echo  "<td>&nbsp;&nbsp;<strong>+</strong>/<strong>-</strong></td>\n";
  echo  "</tr>\n";

 while ($row=mysql_fetch_array($result)) {
  // Extracting & formatting date
  $datetime=date("dMy g:i a",strtotime($row['DateSent']));
  // put in red asterisk if unread & add coloured filters
  if ($row[status]=="unread") {$status="<a title='This message has not been read yet!'><font color=Red>*</font></a>";} else {$status="";}
  if ($row[urgent]=="1") {$urgentmkr="<a title='This is an urgent message!'><font color=Red><strong>!</strong></font></a>";} else {$urgentmkr="";}
  if ($row[repliedto]=="1") {$replied="<a title='You have replied to this message!'><font color='black'><strong>+</strong></black></a>";} else {$replied="&nbsp;";}
  echo "<tr><td>$status$urgentmkr&nbsp;<a href=".$link."?action=view&amp;mail_id=".$row[mail_id]."&amp;page=".$pagenum.">".strip_tags($row[Subject])."</a><small>".$replied."(".$datetime.")</small>";
  // put in asterisks if indicated to do so in database
  if ($row[fltr1]==1) {echo "<font color='red'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
  if ($row[fltr2]==1) {echo "<font color='blue'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
  if ($row[fltr3]==1) {echo "<font color='green'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
  echo "</td>";
  echo "<td>".$this->Format($row[UserFrom])."<small>&nbsp;[<a href=".$link."?action=contacts&amp;cntct=".$row[UserFrom].">-></a>]</small></td><td align='left' width='155'>";

  // code to put in drop down box to move to a new folder
  $str2 = "SELECT DISTINCT info FROM ".$this->config["table_prefix"]."mailinfo WHERE type='folder' and owner='$username' ORDER BY info ASC";
  $resultdrop2 = mysql_query($str2);
  echo "<form method=post action=\"$link&amp;mail_id=$row[mail_id]\"><select name=\"move2folder\">";
    while ($row2 = mysql_fetch_array($resultdrop2)) {
      extract ($row2);
         echo "<option value=\"$info\">$info</option>";
         }
    echo "</select><input type='submit' value='Move'></form>";
    echo "</td><td> [<a href=\"javascript: if(confirm('Are you sure you want to delete this item?')){ window.self.location='".$link."?action=delete&amp;id=".$row[mail_id]."' }\">Delete</a>]<br /></td>";
    echo "</td><td> &nbsp;<a href=".$link."?fltrset=1&amp;mail_id=".$row[mail_id]."&amp;fltr=".$filter."&amp;page=".$pagenum." title='Mark message with a RED star.'><font color='red'><strong>*</strong></font></a>|<a href=".$link."?fltrset=2&amp;mail_id=".$row[mail_id]."&amp;fltr=".$filter."&amp;page=".$pagenum." title='Mark message with a BLUE star.'><font color='blue'><strong>*</strong></font></a>|<a href=".$link."?fltrset=3&amp;mail_id=".$row[mail_id]."&amp;fltr=".$filter."&amp;page=".$pagenum." title='Mark message with a GREEN star.'><font color='green'><strong>*</strong></font></a><br /></td></tr>";
 }
 echo "</table>";
 if ($total_records!=0) {
 echo "<small>&nbsp;&nbsp;&nbsp;Clicking on the right arrow indicator [->] will add the user's name to the \"contacts\" list.<br />&nbsp;&nbsp;&nbsp;A \"+\" sign to the right of the message title indicates that you have replied to the message.</small>";
    }else{
    echo "<br /><em>There are no currently no messages in the in-box <br />(or, none meet the requirements of the applied filter).</em><br /><br />";
 }
}

// send a new message to a user
elseif($action==compose) {
 $subject2=$_GET[subject];
 echo "<em>Compose a message....</em>";
 echo "<table width='675'><tr><td>";
 echo "<form name='myform' action=".$link."?action=compose2 method='post'>";
 echo "<table>";
 echo "<tr><td>Subject:</td><td><input type='text' name='subject' maxlength='65' size='30' value='$subject2'></td></tr>";
 echo "<tr><td>To:</td><td><input type='text' name='to' maxlength='65' size='30' value='$to'></td></tr>";
 echo "<tr><td>Message:</td><td><textarea rows='16' cols='45' name='message' onKeyDown=\"textCounter(this.form.message,this.form.remLen,2000);\" onKeyUp=\"textCounter(this.form.message,this.form.remLen,2000);\"></textarea><br /><input readonly type='text' name='remLen' size='4' maxlength='4' value='2000'> characters left.</td></tr>";
 echo "<tr><td><button type='submit'>Send Mail!</button></td><td align='right'>Urgent? <INPUT TYPE='checkbox' NAME='urgent' VALUE='1'></td></tr>";
 echo "<tr><td></td><td><small>All fields must have content.</small></td></tr></table>";
 echo "</form>";
 echo "</td><td width='200' valign='top'>";
 echo "<strong>Contact List<br /></strong><small>(click on name to add to form)</small><br />";
 $cntctresult = mysql_query("SELECT info FROM ".$this->config["table_prefix"]."mailinfo WHERE type='contact' and owner='$username' ORDER BY info ASC");
 while ($row=mysql_fetch_array($cntctresult)) {
   echo "<a href=".$link."?action=compose&amp;to=".urlencode($row[info]).">".$row['info']."</a><br />";
   }
   echo "</td></tr></table>";
}

// send a reply to message sender
elseif($action==reply) {
 $subject2=$_GET[subject];
 echo "<em>Reply to the message....</em>";
 echo "<table width='400'><tr><td>";
 echo "<form name='myform' action=".$link."?action=compose2&amp;replyto=".$msg_id." method='post'>";
 echo "<tr><td>Subject:</td><td><input readonly type='text' name='subject' maxlength='65' size='30' value='$subject2'></td></tr>";
 echo "<tr><td>To:</td><td><input readonly type='text' name='to' maxlength='65' size='30' value='$to'></td></tr>";
 $result=mysql_query("SELECT * from ".$this->config["table_prefix"]."mail WHERE UserTo='$username' AND mail_id=$mail_id") or die ("cant do it");
 $rowreply=mysql_fetch_array($result);
 $origmsg="&nbsp;\n&nbsp;\n++++++++++ Original Message ++++++++++\n".strip_tags($rowreply[Message])."\n+++++++++++++++++++++++++++++++++";
 echo "<tr><td>Message:</td><td><textarea rows='16' cols='45' name='message' onKeyDown=\"textCounter(this.form.message,this.form.remLen,2000);\" onKeyUp=\"textCounter(this.form.message,this.form.remLen,2000);\">".$origmsg."</textarea><br /><input readonly type='text' name='remLen' size='4' maxlength='4' value='2000'> characters left.</td></tr>";
 echo "<tr><td><button type='submit'>Send Mail!</button></td><td align='right'>Urgent? <INPUT TYPE='checkbox' NAME='urgent' VALUE='1'></td></tr>";
 echo "<tr><td></td><td><small>All fields must have content.</small></td></tr></table>";
 echo "</form>";
}

// send a forwarded message
elseif($action==forward && $mail_id!="") {
 $username = $this->GetUserName();
 echo "<em>Add a message to the forwarded message....</em>";
 echo "<table width='675'><tr><td>";
 echo "<form name='myform' action=".$link."?action=compose2 method='post'>";
 echo "<table>";
 $subject2 = "FWD:&nbsp;".$subject;
 echo "<tr><td>Subject:</td><td><input type='text' name='subject' maxlength='65' size='30' value='$subject2'></td></tr>";
 echo "<tr><td>To:</td><td><input type='text' name='to' maxlength='65' size='30' value='$to'></td></tr>";
 $result=mysql_query("SELECT * from ".$this->config["table_prefix"]."mail WHERE UserTo='$username' AND mail_id=$mail_id") or die ("cant do it");
 $rowfwd=mysql_fetch_array($result);
 $origmsg="&nbsp;\n&nbsp;\n++++++++++++ Forward ++++++++++++++\n".strip_tags($rowfwd[Message])."\n+++++++++++++++++++++++++++++++++";
 echo "<tr><td>Message:</td><td><textarea rows='16' cols='45' name='message' onKeyDown=\"textCounter(this.form.message,this.form.remLen,2500);\" onKeyUp=\"textCounter(this.form.message,this.form.remLen,2500);\">$origmsg</textarea><br /><input readonly type='text' name='remLen' size='4' maxlength='4' value='2500'> characters left.</td></tr>";
 echo "<tr><td><button type=submit>Send Mail!</button></td><td align='right'>Urgent? <INPUT TYPE='checkbox' NAME='urgent' VALUE='1'></td></tr>";
 echo "<tr><td></td><td><small>All fields must have content.</small></td></tr></table>";
 echo "</form>";
 echo "</td><td width='200' valign='top'>";
 echo "<strong>Contact List<br /></strong><small>(click on name to add to form)</small><br />";
 $cntctresult = mysql_query("SELECT info FROM ".$this->config["table_prefix"]."mailinfo WHERE type='contact' and owner='$username' ORDER BY info ASC");
 while ($row=mysql_fetch_array($cntctresult)) {
    echo "<a href=".$link."?action=forward&amp;to=$row[info]&amp;mail_id=$mail_id&amp;subject=".urlencode($subject).">".$row['info']."</a><br />";
 }
 echo "</td></tr></table>";
}

 // enters message from compose window (original or forward) into the database
if($action==compose2) {
 if ($user = $this->GetUser()){
  $urgent=$_POST['urgent'];
  $to=$_POST['to'];
  $to=addslashes($to);
  $subject=$_POST['subject'];
  $subject=addslashes($subject);
  $message=$_POST['message'];
  $message=strip_tags($message);
  $message=addslashes($message);
  $replyto=$_GET['replyto'];
  $date = date(YmdHis);

  // check if user exists & if so sends message

    if($subject=="" || $message=="" || $to==""){
      echo "One of the fields was left blank.";
      }else{
       if($this->LoadUser($to)) {
        $create = "INSERT INTO ".$this->config["table_prefix"]."mail (UserTo, folder, UserFrom, Subject, Message, DateSent, status, urgent)
        VALUES ('$to','inbox','$username','$subject','$message','$date','unread','$urgent')";
        $create2 = mysql_query($create) or die("A letter could not be sent to $to!");
        echo("Message Sent to $to!<br /><br /><br /><br /><br /><br /><br />");
      //to set the database so that the message has been replied to
         mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET repliedto='1' WHERE mail_id='$replyto' AND UserTo='$username'");
    } else {
        echo "The recipient name entered was not a registered user. <br />You might check the upper/lower case of the spelling.";
        }
   }
  }else{
  echo "<br />You must be both <strong>registered</strong> <u>and</u> <strong>logged</strong> in to use this Private Messaging System.<br />";
 }
}


// show sent box
elseif($action=='sent') {
 $query="SELECT * from ".$this->config["table_prefix"]."mail where UserFrom='$username' ORDER BY DateSent DESC";
 $result=mysql_query($query) or die ("cant do it");
 echo "<table cellpadding='2' cellspacing='3' width='750' valign='top'>";
       //needed for pagination of sent box
       $record_per_page=12;
    $total_records=mysql_num_rows($result);
       $scroll=3;
    $page=new Page(); //creating new instance of Class Page
    $link2=$link."?action=sent";
       $page->set_page_data($link2,$total_records,$record_per_page,$scroll,true,true,true);
    $result=mysql_query($page->get_limit_query($query));
    // to paginate the "sent" page messages
    echo "<tr><td colspan='3' align='center'>";   
     if ($total_records>$record_per_page) {echo $page->get_page_nav();}
    echo "</td></tr>";
  echo  "<tr bgcolor=#dddddd>\n";
  echo  "<td width='400'>&nbsp;Message Topic:</td>\n";
  echo  "<td width='85'>&nbsp;Sent to:</td>\n";
  echo  "<td width='75'>&nbsp;Read?</td>\n";
  echo  "</tr>\n";
  while ($row=mysql_fetch_array($result)) {
   $datetime=date("dMy g:i a",strtotime($row['DateSent']));
   echo "<tr><td><a href=".$link."?action=view2&amp;mail_id=".$row[mail_id]."&amp;page=".$pagenum.">".strip_tags($row[Subject])."</a><small>&nbsp;(".$datetime.")</small></td><td>".$this->Format($row[UserTo])."<small>&nbsp;[<a href=".$link."?action=contacts&amp;cntct=".$row[UserTo].">-></a>]</small></td><td width=50>&nbsp;$row[status]<br></td></tr>";
  }
  echo "</table>";
  echo "<small>&nbsp;&nbsp;&nbsp;Clicking on the right arrow indicator [->] will add the user's name to the \"contacts\" list.</small>";
}

// Code to show folders according to selection
elseif((($_REQUEST['whichfolder']!='') || ($folder)) && ($action!=view)) {
 if ($filter==1) {$search="and fltr1='1' ";} elseif ($filter==2) {$search="and fltr2='1' ";} elseif ($filter==3) {$search="and fltr3='1' ";} elseif ($filter==N) {$search="and fltr1='0' and fltr2='0' and fltr3='0' ";} else {$search="";}
 if ($_REQUEST['whichfolder']!='') {$showfolder = $_REQUEST['whichfolder'];} else {$showfolder=$folder;}
 echo "<table cellpadding='2' cellspacing='3' width='850' valign='top'>";
   echo  "<tr bgcolor=#dddddd>\n";
   echo  "<td><table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td>&nbsp;Message Topic:</td><td align='right'>";
   if ($filter==1) {$red="<u>*</u>";} else {$red="*";}
   if ($filter==2) {$blue="<u>*</u>";} else {$blue="*";}
   if ($filter==3) {$green="<u>*</u>";} else {$green="*";}
   if ($filter=="N") {$none="<u>N</u>";} else {$none="N";}
   echo  "<a href=".$link."&amp;folder=".$which."><strong>A</strong></a>&nbsp;<a href=".$link."?fltr=N&amp;folder=".$which."><strong>".$none."</strong></a>&nbsp;<a href=".$link.">?fltr=1&amp;folder=".$which."><font color='red'><strong>".$red."</strong></font></a>&nbsp;<a href=".$link."?fltr=2&amp;folder=".$which.">";
   echo  "<font color='blue'><strong>".$blue."</strong></font></a>&nbsp;<a href=".$link."?fltr=3&amp;folder=".$which."><font color='green'><strong>".$green."</strong></font></a></td></tr></table></td>\n";
   echo  "<td width='65'>&nbsp;Sender:</td>\n";
   echo  "<td width='155'>&nbsp;Move to Folder:</td>\n";
   echo  "<td>&nbsp;Delete:</td>\n";
   echo  "<td>&nbsp;&nbsp;<strong>+</strong>/<strong>-</strong></td>\n";
   echo  "</tr>\n";
  $query="SELECT fltr1,fltr2,fltr3,mail_id FROM ".$this->config["table_prefix"]."mail where UserTo='$username' ".$search."and folder='$folder' and viewrecipient='Y' ORDER BY DateSent DESC";
  $result=mysql_query($query) or die ("cant do it");
  while ($row=mysql_fetch_array($result)) {
   // code to set filters in database
    if (($fltrset) && ($row[mail_id]==$msg_id)) {
       // code to determine setting of filters on server
       if ($row[fltr1]!=1) {$fltrvar1=1;} else {$fltrvar1=0;}
       if ($row[fltr2]!=1) {$fltrvar2=1;} else {$fltrvar2=0;}
       if ($row[fltr3]!=1) {$fltrvar3=1;} else {$fltrvar3=0;}
       // code to set which filter is being set
       if ($fltrset==1) {$fltr="fltr1"; $set=$fltrvar1;} elseif ($fltrset==2) {$fltr="fltr2"; $set=$fltrvar2;} elseif ($fltrset==3) {$fltr="fltr3"; $set=$fltrvar3;}
       mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET ".$fltr."=".$set." WHERE mail_id='$msg_id' AND UserTo='$username'");
    }
  }

 $result=mysql_query("SELECT * from ".$this->config["table_prefix"]."mail where UserTo='$username' ".$search."AND folder='$showfolder' ORDER BY DateSent DESC") or die ("cant do it");
 $numrows=mysql_num_rows($result);
    while ($row=mysql_fetch_array($result)) {
    $datetime=date("dMy g:i a",strtotime($row['DateSent']));
    if ($row[status]=="unread") {$status="<a title='This message has not been read yet!'><font color=Red>*</font></a>";} else {$status="";}
       if ($row[urgent]=="1") {$urgentmkr="<a title='This is an urgent message!'><font color=Red><strong>!</strong></font></a>";} else {$urgentmkr="";}
    if ($row[repliedto]=="1") {$replied="<a title='You have replied to this message!'><font color='black'><strong>+</strong></black></a>";} else {$replied="&nbsp;";}
    echo "<tr><td>$status$urgentmkr&nbsp;<a href=".$link."?action=view&amp;mail_id=$row[mail_id]&amp;folder=".$which.">".strip_tags($row[Subject])."</a>".$replied."<small>(".$datetime.")</small>";
      // put in asterisks if indicated to do so in database
      if ($row[fltr1]==1) {echo "<font color='red'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
      if ($row[fltr2]==1) {echo "<font color='blue'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
      if ($row[fltr3]==1) {echo "<font color='green'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
    echo "</td><td width=125>".$this->Format($row[UserFrom])."<small>&nbsp;[<a href=".$link."?action=contacts&amp;cntct=".$row[UserFrom].">-></a>]</small></td><td>";

      // code to put in drop down box to move to a new folder
      $str2 = "SELECT DISTINCT info FROM ".$this->config["table_prefix"]."mailinfo WHERE type='folder' and owner='$username' ORDER BY info ASC";
      $resultdrop2 = mysql_query($str2);
    echo "<form method=post action=\"$link?mail_id=$row[mail_id]&amp;folder=$which\"><select name=\"move2folder\">";
       while ($row2 = mysql_fetch_array($resultdrop2)) {
        extract ($row2);
           echo "<option value=\"$info\">$info</option>";
       }
      echo "</select><input type='submit' value='Move'></form>";
      echo "</td><td> [<a href=\"javascript: if(confirm('Are you sure you want to delete this item?')){ window.self.location='".$link."?action=delete&amp;id=".$row[mail_id]."' }\">Delete</a>]<br /></td>";
      echo "</td><td> &nbsp;<a href=".$link."?fltrset=1&amp;mail_id=".$row[mail_id]."&amp;folder=".$which."&fltr=".$filter."><font color='red'><strong>*</strong></font></a>|<a href=".$link."?fltrset=2&amp;mail_id=".$row[mail_id]."&amp;folder=".$which."&fltr=".$filter."><font color='blue'><strong>*</strong></font></a>|<a href=".$link."?fltrset=3&amp;mail_id=".$row[mail_id]."&amp;folder=".$which."&fltr=".$filter."><font color='green'><strong>*</strong></font></a><br /></td></tr>";
      }
   echo "</table>";
 if ($numrows==0) {echo "<br /><em>There are no messages currently stored <br />in this folder (or, with this filter).</em><br /><br />"; }
}

// view individual email messages
elseif($action==view) {
 $result=mysql_query("select * from ".$this->config["table_prefix"]."mail where UserTo='$username' and mail_id=$msg_id") or die ("cant do it");
 $row=mysql_fetch_array($result);
    if (($fltrset) && ($row[mail_id]==$msg_id)) {
       // code to determine setting of filters on server
       if ($row[fltr1]!=1) {$fltrvar1=1;} else {$fltrvar1=0;}
       if ($row[fltr2]!=1) {$fltrvar2=1;} else {$fltrvar2=0;}
       if ($row[fltr3]!=1) {$fltrvar3=1;} else {$fltrvar3=0;}
       // code to set which filter is being set
       if ($fltrset==1) {$fltr="fltr1"; $set=$fltrvar1;} elseif ($fltrset==2) {$fltr="fltr2"; $set=$fltrvar2;} elseif ($fltrset==3) {$fltr="fltr3"; $set=$fltrvar3;}
       mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET ".$fltr."=".$set." WHERE mail_id='$msg_id' AND UserTo='$username'");
    }
 $result=mysql_query("select * from ".$this->config["table_prefix"]."mail where UserTo='$username' and mail_id=$msg_id") or die ("cant do it");
 $row=mysql_fetch_array($result);
 $username=strtolower($username);
 $row[UserTo]=strtolower($row[UserTo]);
 if ($row[repliedto]=="1") {$replied="<a title='You have replied to this message at least once!'><font color='black'><small>replied to<small></black></a>";} else {$replied="&nbsp;";}
   // code to set filters in database
  if($row[UserTo]==$username) {
    $query="UPDATE ".$this->config["table_prefix"]."mail SET status='read' WHERE UserTo='$username' AND mail_id='$row[mail_id]'";
    $query or die("An error occurred resulting that this message has not been marked read.");
    $datetime=date("dMy g:i a",strtotime($row['DateSent']));
    echo "<table border='1' bordercolor='#666699' width='600'><tr><td width='350'><strong>Subject: </strong>".strip_tags($row[Subject])."&nbsp;";
      // put in asterisks if indicated to do so in database
      if ($row[fltr1]==1) {echo "<font color='red'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
      if ($row[fltr2]==1) {echo "<font color='blue'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
      if ($row[fltr3]==1) {echo "<font color='green'><strong>*</strong></font>";} else {echo "&nbsp;&nbsp;";}
    echo "</td><td>";
    echo "&nbsp;<a href=".$link."?action=view&amp;fltrset=1&amp;mail_id=".$row[mail_id]." title='Mark message with a RED star.'><font color='red'><strong>*</strong></font></a>|<a href=".$link."?action=view&amp;fltrset=2&amp;mail_id=".$row[mail_id]." title='Mark message with a BLUE star.'><font color='blue'><strong>*</strong></font></a>|<a href=".$link."?action=view&amp;fltrset=3&amp;mail_id=".$row[mail_id]." title='Mark message with a GREEN star.'><strong>*</strong></font></a>";
    echo "</td><td><strong>From: </strong>".$this->Format($row[UserFrom])."<small>&nbsp;[<a href=".$link."?action=contacts&amp;cntct=".$row[UserFrom].">-></a>]</small></td></tr>";
    echo "<tr><td colspan='3'><strong>Message: </strong>".strip_tags($row[Message])."</td></tr><tr><td><a href=".$link."?action=reply&amp;to=".$row[UserFrom]."&amp;mail_id=".$row[mail_id]."&amp;subject=RE:".urlencode($row[Subject]).">Reply</a> / <a href=".$link."?action=forward&amp;mail_id=$row[mail_id]&amp;subject=RE:".urlencode($row[Subject]).">Forward</a>";
    echo " / <a href=\"javascript: if(confirm('Are you sure you want to delete this item?')){ window.self.location='".$link."?action=delete&amp;id=".$mail_id."' }\">Delete</a></td><td>".$replied."</td><td><small><strong>Sent:</strong> $datetime</small></td></tr></table><br />";
    $rs = mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET status='read' WHERE mail_id='$msg_id'");
    } else {
    echo "<font face=verdana><strong>This isn't your mail!";    
    }
  echo "<small>&nbsp;&nbsp;&nbsp;Clicking on the right arrow indicator [->] will add the sender's name to the \"contacts\" list.</small>";
}

// added filter for viewing "folder sorted" mail
elseif($action==view2) {
 $result=mysql_query("SELECT * from ".$this->config["table_prefix"]."mail where UserFrom='$username' and mail_id='$msg_id'") or die ("cant do it");
 $row=mysql_fetch_array($result);
 $username=strtolower($username);
 $userfrom=strtolower($row[UserFrom]);
 if($userfrom==$username) {
    $datetime=date("dMy g:i a",strtotime($row['DateSent']));
    echo "<table border = '1' bordercolor = 'black' width = '600'><tr><td colspan='2' valign='top'><strong>Subject:</strong> ".strip_tags($row[Subject])."</td></tr><tr>";
    echo "<td colspan='2'><strong>Recipient:</strong>&nbsp;".$this->Format($row[UserTo])."<small>&nbsp;[<a href=".$link."?action=contacts&amp;cntct=".$row[UserTo].">-></a>]</small></td></tr><tr><td colspan='2'><strong>Message: </strong>$row[Message]</td></tr><tr><td colspan='2'><small><strong>Sent: </strong>".$datetime."</small></td></tr></table>";
 }
 echo "<small>&nbsp;&nbsp;&nbsp;Clicking on the right arrow indicator [->] will add the sender's name to the \"contacts\" list.</small>";
}

// DELETE code for messages (now updates so that message is not visible instead of deleting)
elseif($action==delete) {
    $query="UPDATE ".$this->config["table_prefix"]."mail SET viewrecipient='N' WHERE UserTo='$username' AND mail_id='$id'";
    $query or die("An error occurred resulting that this message has not been marked read.");
    $rs = mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET viewrecipient='N' WHERE mail_id='$id'");
    if($query) {
    echo "<font face=verdana>Message was deleted.<br /><br /><br /><br /><br /><br /><br /></font>";
        } else {
        echo "The message was not deleted.";
    }
}

// code to manage contact list
elseif ($action==contacts){
 $addcontact=$_GET['cntct'];
 $table = $this->config["table_prefix"]."mailinfo";
 $field1 = "info";
 $field1_label = "Contact Names";
 $field2 = "notes";
 $field2_label = "Notes";
 $deletecnt = $_GET['deletecnt'];
 $field1_value=$_POST['field1_value'];
 if ($field1_value) {$insert="1";} else {$insert="";}
 $field2_value=$_POST['field2_value'];
 $category="contact";

 if ($user = $this->GetUser()){
   if ($insert) {
    if($this->LoadUser($field1_value)) {
    mysql_query( "INSERT into $table ($field1, $field2, owner, type) values (\"$field1_value\",\"$field2_value\",\"$username\",\"$category\")");
    }
   }
  if ($deletecnt) {
    mysql_query( "DELETE from $table WHERE id=$deletecnt AND owner='$username'");
  } 
  if (mysql_errno()!=0) {
    switch (mysql_errno()) {
      default:
        echo  "Error #".mysql_errno(). " (".mysql_error(). ")<br>";
    }
   }
 }
  $query =  "SELECT * from $table WHERE owner='$username' AND type='$category' ORDER BY info ASC";
  $result = mysql_query($query);
  $rows = mysql_num_rows($result);
  echo  "<strong><em>Contact Management</em></strong>";
  echo  "<table border='1' cellspacing='0'>\n";
  echo  "<tr>\n";
  echo  "<td><strong>$field1_label</strong></td>\n";
  echo  "<td><strong>$field2_label</strong></td>\n";
  echo  "<td>&nbsp;</td>\n";
  echo  "</tr>\n";
 // This is the entry boxes
  echo  "<form action=\"$link?action=contacts\" method=\"post\">\n";
  echo  "<tr>\n";
  echo  "<input type='hidden' name='insert' value='1'></td>\n";
  echo  "<td><input type='text' size='20' maxlength='65' name='field1_value' value='$addcontact'></td>\n";
  echo  "<td><input type='text' size='35' maxlength='65' name='field2_value'></td>\n";
  echo  "<td colspan=2 align=center>";
  echo  "<input type='submit' value=\"   Add    \"></td>\n";
  echo  "</tr>\n";
  echo  "</form>\n";
 // This is the data under the entry boxes
      while ($row = mysql_fetch_row($result)) {
      echo  "<tr>\n";
      echo  "<td><a href=".$link."?action=compose&amp;to=".$row[2].">".$row[2]."</a><small>&nbsp;&nbsp;[<a href=".$this->config["base_url"].$row[2].">Home Page</a>]</small></td>\n";
         echo  "<td>".strip_tags($row[3])."</td>\n";
      echo  "<td><a href=\"javascript: if(confirm('Are you sure you want to delete this item?')){ window.self.location='".$link."?action=contacts&amp;deletecnt=".$row[4]."' }\"><center>Delete</center></a></td>\n";
      echo  "</tr>\n";
      }
  echo "</table>";
  echo "<small>Clicking on the contact name will take you to message entry screen.</small>";
}

// code to manage folder list
elseif ($action==folders){
 $table = $this->config["table_prefix"]."mailinfo";
 $field1 = "info";
 $field1_label = "Folder List";
 $field2 = "notes";
 $field2_label = "Notes";
 $deletefldr = $_GET['deletefldr'];
 $fldr = $_GET['fldr'];
 $field1_value=$_POST['field1_value'];
 if ($field1_value) {$insert="1";} else {$insert="";}
 $field2_value=$_POST['field2_value'];
 $category="folder";

 if ($user = $this->GetUser()){
  if ($insert) {
        mysql_query( "INSERT into $table ($field1, $field2, owner, type) values (\"$field1_value\",\"$field2_value\",\"$username\",\"$category\")");
  }

  if ($deletefldr) {
  // delete folder name from mailinfo
    mysql_query("DELETE from $table WHERE id='$deletefldr' AND owner='$username' AND type='folder'");
  // change files from being stored in folder being deleted to being stored in inbox
    mysql_query("UPDATE ".$this->config["table_prefix"]."mail SET folder='inbox' WHERE folder='$fldr' AND UserTo='$username'");
  } 
 
  if (mysql_errno()!=0) {
   switch (mysql_errno()) {
    default:
       echo  "Error #".mysql_errno(). " (".mysql_error(). ")<br>";
   }
  }
 }
  $query =  "SELECT * from $table WHERE owner='$username' AND type='$category' ORDER BY info ASC";
  $result = mysql_query($query);   
  $rows = mysql_num_rows($result);
  echo  "<strong><em>Folder Management</em></strong>";
  echo  "<table border='1' cellspacing='0'>\n";
  echo  "<tr>\n";
  echo  "<td><strong>$field1_label</strong></td>\n";
  echo  "<td><strong>$field2_label</strong></td>\n";
  echo  "<td>&nbsp;</td>\n";
  echo  "</tr>\n";

 // This is the entry boxes
  echo  "<form action=\"$link?action=folders\" method=\"post\">\n";
  echo  "<tr>\n";
  echo  "<input type='hidden' name='insert' value='1'></td>\n";
  echo  "<td><input type='text' size='25' maxlength='65' name='field1_value'></td>\n";
  echo  "<td><input type='text' size='35' maxlength='65' name='field2_value'></td>\n";
  echo  "<td colspan='2' align='center'>";
  echo  "<input type='submit' value=\"   Add    \"></td>\n";
  echo  "</tr>\n";
  echo  "</form>\n";
 // This is the data under the entry boxes
      while ($row = mysql_fetch_row($result)) {
      echo  "<tr>\n";
      echo  "<td><a href=".$link."?folder=".strip_tags($row[2]).">".strip_tags($row[2])."</a></td>\n";
         echo  "<td>".strip_tags($row[3])."</td>\n";
      echo  "<td><a href=\"javascript: if(confirm('Are you sure you want to delete this item?')){ window.self.location='".$link."?action=folders&amp;deletefldr=".$row[4]."&amp;fldr=".$row[2]."' }\">
  <center>Delete</center></a></td>\n";
      }
  echo "</table>";
  echo "<small>Clicking on the folder name will take you to that folder.</small>";
}

// code to display user list
elseif ($action==users){
 echo "<table width='650'><tr><td>"; 
 $last_users = $this->LoadAll("select name from ".$this->config["table_prefix"]."users order by name ASC");
 echo "<strong><em>User List.</em></strong> Click on the name to add it to the contact list.<br />";
  foreach($last_users as $user) {
    echo "<a href=".$link."?action=contacts&amp;cntct=".$user["name"].">".$user["name"]."</a> ";
   }
  echo "</td></tr></table>";
}

//code to show brief instructions for using filters
elseif ($action==help){
echo "<table width='700'><tr><td>";
echo "<p><strong>An introduction to sending messages in Wikka...</strong></p>";
echo "There are two brief parts to this help file. The first is how to interpret the output screen. The second is a description of how filters work.<br /><br />";
echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><em>Introduction to the output...</em></strong><br /><br />";
echo "Below is a typical output line in the In-Box, Folder lists or the Sent message area.<br /><br />";
echo "<table border='0' width='800'>";
echo "<tr><td valign='middle'>";
echo "<P>&nbsp;<font color='#FF0000'><strong>!* </strong></font><A>Science Class tomorrow</A><font color='#000000'><strong><a title='You have answered this email.'>&nbsp;</a></strong><small>(05Feb05 2:08 pm)</small></font><font color='#FF0000'><strong>*</strong></font><font color='#000000'>&nbsp;&nbsp;</font><font color='#008000'><strong>*</strong></font></P>";
echo "</td><td align='center' width='140' valign='middle'>";
echo "<P><a title='Sender'>GmBowen</a><small>&nbsp;&#91;<a title='Put into contact list.'>-&gt;</a>&#93;</small></P>";
echo "</td>";
echo "<td width='150' valign='middle'>";
echo "<P><form>";
echo "<P><select name=move2folder>";
echo "<option value=ColeBowen>ColeBowen";
echo "<option value=GmBowen>GmBowen";
echo "<option value=Personal>Personal";
echo "<option value=Work>Work";
echo "</select><input type='button' name='Submit' value='Move'>";
echo "</form></P>";
echo "</td>";
echo "<td align='center' valign='middle' width='60'>";
echo "<P align='center'>&#91;<a>Delete</a>&#93;</P>";
echo "</td>";
echo "<td width='53'>";
echo "<P>&nbsp;<A title='Mark message with a RED star.'></A><font color='#FF0000'><strong>*</strong></font>|<A title='Mark message with a BLUE star.'></A><font color='#0000FF'><strong>*</strong></font>|<A  title='Mark message with a GREEN star.'></A><font color='#008000'><strong>*</strong></font><BR>";
echo "</P>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</font><font color='#000000'><br />Here is how to interpret the output....</font></P>";
echo "<UL>";
echo "<LI><font color='#000000'>The exclamation mark (</font><font color='#FF0000'><strong>!</strong></font><font color='#000000'>) tells you that the sender marked the message <strong>urgent</strong>.</font></LI>";
echo "<LI><font color='#000000'>The first red star (</font><font color='#FF0000'>*</font><font color='#000000'>) tells you that you have not read the message yet. </font></LI>";
echo "<LI><font color='#000000'>'Science Class tomorrow' is the topic of the message.</font></LI>";
echo "<LI><font color='#000000'>If there were a plus sign (<strong>+</strong>) immediately after the topic you would know that you had replied to the message. </font></LI>";
echo "<LI><font color='#000000'>The date/time after the message lets you know when the message was sent. </font></LI>";
echo "<LI><font color='#000000'>The coloured stars after the date/time (</font><font color='#FF0000'>*&nbsp;</font><font color='#000000'>&nbsp;</font><font color='#00FF00'>*</font><font color='#000000'>) indicate that you've applied those two markers to your message (see below). </font></LI>";
echo "<LI><font color='#000000'>'GmBowen' is the sender of the message.</font></LI>";
echo "<LI><font color='#000000'>The &#91;-&gt;&#93; allows you to put the senders name into your contact list. </font></LI>";
echo "<LI><font color='#000000'>The dropdown menu (starting with 'ColeBowen') is a list of folders that you can file the message into. </font></LI>";
echo "<LI><font color='#000000'>The &#91;</font><font color='#0000FF'>Delete</font><font color='#000000'>&#93; button allows you to delete the message (even though it does stay in the database). </font></LI>";
echo "<LI><font color='#000000'>Clicking on the three coloured stars (</font><font color='#FF0000'>*</font><font color='#000000'>|</font><font color='#0000FF'>*</font><font color='#000000'>|</font><font color='#00CC00'>*</font><font color='#000000'>) allow you to set markers on your messages.</font></LI>";
echo "</UL>";
echo "<br /><br />";
echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><em>Introduction to filters...</em></strong><br /><br />";
echo "<P>'Filters' are a simple-to-use tool that can help you organize your\n";
echo "messages.</P>\n";
echo "\n";
echo "<P>When you're in the in-box or any of the folders, on the top right\n";
echo "of the title bar you'll see a +/- with\n";
echo "<font color='#FF0000'>*</font>|<font color='#0000FF'>*</font>|<font color='#008000'>*\n";
echo "</font>underneath it (and to the right of each message). By clicking\n";
echo "on these three coloured stars you can place or remove coloured stars\n";
echo "from beside the message title. A similar feature is found inside each\n";
echo "individual message box (seen when you're reading your messages).</P>\n";
echo "\n";
echo "<P>The different colours can mean anything you want them to. Red\n";
echo "might mean 'really important' and green might mean 'Ignore for now'.\n";
echo "It's really up to you. They can mean different things to you in your\n";
echo "in-box versus your different folders as well</P>\n";
echo "\n";
echo "<P><table>\n";
echo "<tr bgcolor='#DDDDDD'>\n";
echo "<td width='400'>\n";
echo "<P><table border='0' cellspacing='0' cellpadding='0' width='100%'>\n";
echo "<tr>\n";
echo "<td>\n";
echo "<P>&nbsp;Message Topic:</P>\n";
echo "</td>\n";
echo "<td align=right>\n";
echo "<P><strong>A</strong>&nbsp;<strong>N</strong>&nbsp;<font color='#FF0000'><strong>*</strong></font>&nbsp;<font color='#0000FF'><strong>*</strong></font>&nbsp;<strong>*</strong></P>\n";
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</P>\n";
echo "</td>\n";
echo "<td width='85'>\n";
echo "<P>&nbsp;Sender:</P>\n";
echo "</td>\n";
echo "<td width='155'>\n";
echo "<P>&nbsp;Move to Folder:</P>\n";
echo "</td>\n";
echo "<td>\n";
echo "<P>&nbsp;Delete:</P>\n";
echo "</td>\n";
echo "<td width='45'>\n";
echo "<P>&nbsp;&nbsp;<strong>+</strong>/<strong>-</strong></P>\n";
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</P>\n";
echo "\n";
echo "<P>On the grey title bar to the right of 'Message Topic:' you can see\n";
echo "&nbsp;<strong>A</strong>&nbsp;<strong>N</strong>&nbsp;\n";
echo "<font color='#FF0000'>*</font>&nbsp;<font color='#0000FF'>*</font>&nbsp;<font color='#008000'>*</font></P>\n";
echo "\n";
echo "<P>By clicking on the '<strong>A</strong>'&nbsp;you'll see all of the messages,\n";
echo "on the '<strong>N</strong>' you'll see the messages that don't have any markers\n";
echo "beside them, and if you click on any of the coloured stars you'll see\n";
echo "the messages that have those coloured markers beside them.</P>\n";
echo "\n";
echo "<P>Easy eh?&nbsp;</P>\n";
echo "</td></tr></table>";
}
?>